package utils

import (
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"math/rand"
	"strconv"
)

var SigningKey = []byte("Y2NlNDU3dDZlaTMkJV4zMjEyLTMwOTI0V0VGI0VGZHNlc2RldyYkMw")

type MyCustomClaims struct {
	UserId   int    `json:"user_id"`
	UserName string `json:"user_name"`
	jwt.RegisteredClaims
}

func GenerateToken(userId int, username string) (token string, err error) {
	claims := MyCustomClaims{userId, username,
		jwt.RegisteredClaims{
			ID:      strconv.Itoa(rand.Int()),
			Subject: "116010030@qq.com",
		},
	}
	withClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, &claims)
	return withClaims.SignedString(SigningKey)
}

func CheckToken(token string) (b bool) {
	_, err := jwt.ParseWithClaims(token, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return SigningKey, nil
	})
	return err != nil
}
